$( function()
{
	scrollTop();
	if( $( window ).scrollTop() >= 20 )
	{
		$( 'header' ).addClass( 'active' )
	}
	else
	{
		$( 'header' ).removeClass( 'active' )
	}
	if( $( window ).scrollTop() >= 200 )
	{
		$( '.banner .search-wrap' ).addClass( 'active' )
	}
	else
	{
		$( '.banner .search-wrap' ).removeClass( 'active' )
	}
	$( window ).on( 'scroll', function()
	{
		var scrollTop = $( document ).scrollTop();
		if( scrollTop >= 300 )
		{
			$( '.scrollTop' ).show()
		}
		else
		{
			$( '.scrollTop' ).hide()
		}
		if( scrollTop >= 20 )
		{
			$( 'header' ).addClass( 'active' )
		}
		else
		{
			$( 'header' ).removeClass( 'active' )
		}
		if( scrollTop >= 200 )
		{
			$( '.banner .search-wrap' ).addClass( 'active' )
		}
		else
		{
			$( '.banner .search-wrap' ).removeClass( 'active' )
		}
	} );

	/*我的选品高度自适应*/
	var WHeight = $( window ).height();//可视窗口高度
	$( ".mySelection" ).height( WHeight + "px" );
	var leftAreaHeight = $( ".mySelection .leftArea" ).height();
	$( ".mySelection .shrinkBtn" ).css( "marginTop", leftAreaHeight / 2 - 67.5 + "px" );

	//根据登录状态和身份显示header操作元素

	//查询本地登录状态缓存loginFlag
	var loginFlag = getStorage( "loginFlag" );
	var userMsg = JSON.parse( getStorage( "userMsg" ) );
	if( loginFlag == null )
	{//不存在-非登录状态
		$( ".head-right" ).show();
	}
	else
	{//存在
		var loginTime = parseInt( getStorage( "loginTime" ) );
		var nowTime = new Date().getTime();
		if( nowTime - loginTime < (24 * 60 * 60 * 1000) )
		{//未超出24小时，登录状态有效
			$( ".head-right2" ).show();
			//实时获取头像/未读消息
			var token = userMsg.token;
			var mobile = userMsg.mobile;
			$.ajax( {
				type: "POST",
				url: ajaxUrl + "/user/tlogin",
				data: { "token": token, "mobile": mobile },
				success: function( data )
				{
					console.log( JSON.stringify( data ) );
					if( data.code == 0 )
					{
						var icon = data.data.icon == "" || data.data.icon == undefined ? '../../img/default_head.png' : data.data.icon;
						$( ".head-right2 .headPic" ).attr( "src", icon );
						$( ".informNum" ).text( data.data.unreadMessageNum );//未读消息数量
						if(data.data.status==1){//当前禁用
							$(".submitNewBtn,.head-right2 .releaseIcon").addClass("unable");
						}
					}
				},
				error: function( data )
				{
					$.tooltip( data.message );
				}
			} );
			var rolecode = userMsg.rolecode;//1-淘客；2-审核人员
			if( rolecode == 2 )
			{//如果是管理员，隐藏提交和消息按钮，隐藏我的选品
				$( ".releaseIcon,.informIcon,.informNum" ).hide();
				$(".mySelection").hide();
			}else{//淘客
				getCollection();//获取选品
			}
			
		}
		else
		{//超出24小時，登录状态无效-清除loginFlag和loginTime
			localStorage.removeItem( "loginFlag" );
			localStorage.removeItem( "loginTime" );
			//验证token
			$.ajax( {
				type: "POST",
				url: ajaxUrl + "/user/tlogin",
				data: { "token": token, "mobile": mobile },
				success: function( data )
				{
					console.log( JSON.stringify( data ) );
					if( data.code == 0 )
					{//验证成功
						$( ".head-right2" ).show();
						var newUserMsg = data.data;
						//头像
						var icon = newUserMsg.icon == undefined ? '../../img/default_head.png' : newUserMsg.icon;
						$( ".head-right2 .headPic" ).attr( "src", icon );
						if(data.data.status==1){//当前禁用
							$(".submitNewBtn,.head-right2 .releaseIcon").addClass("unable");
						}

						var rolecode = newUserMsg.rolecode;//1-淘客；2-审核人员
						if( rolecode == 2 )
						{
							$( ".releaseIcon,.informIcon,.informNum" ).hide();
						}else{
							$( ".informNum" ).text( newUserMsg.unreadMessageNum );//未读消息数量
							getCollection();//获取选品
						}
						//更新本地缓存
						setStorage( "loginFlag", true );//登录状态
						setStorage( "loginTime", new Date().getTime() );//登录时间
						setStorage( "usercode", data.data.usercode );
						setStorage( "userMsg", JSON.stringify( newUserMsg ) );//用户信息存入localstorage

					}
					else
					{//验证不成功
						localStorage.removeItem( "userMsg" );
						$( ".head-right" ).show();
					}
				},
				error: function( data )
				{
					$.tooltip( data.message );
				}

			} );
		}
	}

	
	//升级公告
	/*var noticeContent='<div class="notice2"> ' +
						'<img src="../../img/notice2.png" alt=""> ' +
						'<i class="iconfont" onclick="$(\'.notice2\').remove();">&#xe613;</i> ' +
						'</div>';
	$("body").append(noticeContent);*/

} );

// 搜索 
$( document ).on( 'focus', '.search-wrap .left input', function()
{
	//清空历史搜索项目
	$( ".searchHistory" ).empty();
	//加载历史搜索项
	var historyItems = localStorage.getItem( "historyItems" );
	console.log( historyItems );
	var s = '';
	if( historyItems == null )
	{ //无历史搜索记录
		s = '<div class="historyItem noItem">暂无历史搜索记录...</div>';
		$( ".searchHistory" ).append( s ).show();
	}
	else
	{//有历史搜索记录
		var strs = historyItems.split( ',' ); //转化为数组
		console.log( strs );
		for( var i = 0; i < strs.length; i++ )
		{
			var itemName = strs[ i ];
			s += '<div class="historyItem" onclick="clickHistoryItem(this);">' + itemName + '</div>';
		}
		$( ".searchHistory" ).append( s ).show();
	}

	//回车搜索
	$( window ).on( 'keyup', function( event )
	{
		var e = event || window.event || arguments.callee.caller.arguments[ 0 ];
		if( e.keyCode == 13 )
		{
			var k = $( '.search-wrap' ).find( 'input' ).val();
			go_search( k );
		}
	} )
} );
//输入框失去焦点，隐藏历史记录
$( document ).on( 'blur', '.search-wrap .left input', function()
{
	//判断点击事件的对象，不是历史记录项或输入框，则隐藏历史记录区域
	$( document ).click( function( e )
	{
		e = window.event || e;
		var obj = e.srcElement || e.target;
		if( !$( obj ).is( ".search-wrap .left .historyItem" ) && !$( obj ).is( ".search-wrap .left input" ) )
		{
			$( ".searchHistory" ).hide();
		}
	} );

} );
//点击历史内容，替换搜索关键字并搜索
function clickHistoryItem( parm )
{
	var k = $( parm ).text();
	window.location.href = 'search.html?keyword=' + k;
	go_search( k );
}

//点击搜索键搜索
$( document ).on( 'click', '.search-wrap .right', function()
{
	var k = $( this ).prev( '.left' ).find( 'input' ).val();
	go_search( k );
} );

//搜索
function go_search( k )
{
	if( isNull( k ) )
	{
		return $.dialog( 'alert', '搜索', '关键词不能为空', 1500 );
	}
	else
	{//非空，存储到历史记录本地缓存
		setHistoryItems( k );
	}
	console.log( checkUrl( k ), getParams( k, 'id' ) );
	if( checkUrl( k ) )
	{ // 如果是链接
		var id = getParams( k, 'id' );
		if( isNull( id ) || !checkID( id ) )
		{
			return $.dialog( 'alert', '搜索', '当前链接不符合商品链接规则', 2000 );
		}
		else
		{
			k = id;
		}
	}
	window.location.href = 'search.html?keyword=' + k;
}
//存值搜索历史,新的值添加在首位，并去重
function setHistoryItems( keyword )
{
	/*localStorage.clear();*/
	console.log( localStorage );
	var historyItems = localStorage.getItem( "historyItems" );
	if( historyItems == null )
	{
		var itemArr = [];
		itemArr[ 0 ] = keyword;
		var itemStr = itemArr.toString();
		localStorage.setItem( "historyItems", itemStr );
	}
	else
	{
		var arr = historyItems.split( ',' );
		//遍历去重
		for( var i = 0; i < arr.length; i++ )
		{
			if( keyword == arr[ i ] )
			{
				console.log( i );
				arr.splice( i, 1 );
			}
		}
		arr.unshift( keyword );
		if( arr.length == 11 )
		{
			arr.splice( 10, 1 );
		}
		localStorage.setItem( "historyItems", arr.toString() );
	}
}
//点击返回页面最顶部
$( document ).on( 'click', '.scrollTop', function()
{
	$( 'html,body' ).animate( { scrollTop: '0px' }, 500 );
} );

//出现审核/下架按钮区域
$( document ).on( 'mouseenter', '.goods-wrap .item', function()
{
	var handleArea = $( this ).find( '.handleArea' );
	if( handleArea.is( ":hidden" ) )
	{
		handleArea.slideDown( 200 );
	}

} );
//出现复制文案按钮
$( document ).on( 'mouseenter', '.goods-wrap .item1', function()
{
	var copybtn = $( this ).find( '.copy-btn' );
	if( copybtn.is( ":hidden" ) )
	{
		copybtn.slideDown( 200 );
	}
} );
//隐藏审核/下架按钮区域
$( document ).on( 'mouseleave', '.goods-wrap .item', function()
{
	var handleArea = $( this ).find( '.handleArea' );
	handleArea.slideUp( 200 );
} );
//隐藏复制文案按钮
$( document ).on( 'mouseleave', '.goods-wrap .item1', function()
{
	var copybtn = $( this ).find( '.copy-btn' );
	copybtn.slideUp( 200 );
} );

// 图片懒加载
function imgLazyLoad()
{
	$( ".scrollLoading" ).lazyload( {
		placeholder: "https://img.alicdn.com/imgextra/i4/1072286858/TB2xuvQt3NlpuFjy0FfXXX3CpXa_!!1072286858.png",
		effect: "fadeIn",
		threshold: 200
	} );
}
//加载
function loading( bgColor, spinner, img )
{
	$( '.fakeloader' ).show();
	$( ".fakeloader" ).fakeLoader( {
		timeToHide: 9999999999999999,
		bgColor: bgColor,
		spinner: spinner
		// imagePath:"../lib/images/google.png"
	} );
}
//加载完成
function loading_success( bgColor, spinner, img )
{
	$( ".fakeloader" ).fakeLoader( {
		timeToHide: 0,
		bgColor: bgColor,
		spinner: spinner,
		// imagePath:"../lib/images/google.png"
	} );
}

function copy_int()
{
	//出现文案
	$( document ).on( 'mouseenter', '.copy-btn,.copyBtn', function()
	{
		console.log( 1 );
		layer.tips( $( this ).attr( 'copy-data' ), this, {
			tips: [ 2, 'rgba(3,169,244,.9)' ],
			time: 0,
			area: '300px'
		} );
		$( '.copy-data' ).html( $( this ).attr( 'copy-data' ) );
	} );

	// 关闭文案
	$( document ).on( 'mouseleave', '.copy-btn,.copyBtn', function()
	{
		layer.closeAll( 'tips' );
	} );

	//复制文案
	var clipboard = new Clipboard( ".copy-btn,.copyBtn" );
	clipboard.on( "success", function( a )
	{
		layer.msg( '<span style="font-size:12px;color:#fff">复制成功</span>' )
	} );
	clipboard.on( "error", function( a )
	{
		layer.msg( '<span style="font-size:12px;color:#fff">复制失败,重新复制试试,或者暂不支持当前浏览器,换个浏览器试试吧</span>' )
	} )
}

$( window ).on( "resize", function()
{
	scrollTop();
} );

function scrollTop()
{
	var b = ($( window ).width() - $( ".wrap" ).width()) / 2;
	var a = b - $( ".scrollTop" ).width() - 48;
	$( ".scrollTop" ).css( "right", a );
}

function isNull( s )
{
	return !s && s !== 0 && typeof s !== "boolean" ? true : false;
}

function formatSort( s )
{
	if( s.toString().length == 1 )
	{
		s = '00' + s;
	}
	else
		if( s.toString().length == 2 )
		{
			s = '0' + s;
		}
	return s;
}
//链接验证
function checkUrl( url )
{
	if( (url.indexOf( "http://" ) >= 0 || url.indexOf( "https://" ) >= 0) )
	{
		return true;
	}
	else
	{
		return false;
	}
}
//商品ID验证
function checkID( s )
{
	var re = /^[0-9]\d{7,11}$/;
	if( !re.test( s ) ) return false;
	return true;
}
//获取当前url里面的参数
function GetQueryString( key )
{
	var url = window.location.href.replace( '?', '&' ).split( '&' );
	var paramsObj = {};
	for( var i = 0, iLen = url.length; i < iLen; i++ )
	{
		var param = url[ i ].split( '=' );
		paramsObj[ param[ 0 ] ] = param[ 1 ];
	}
	if( key )
	{
		return decodeURI( paramsObj[ key ] );
	}
}
//获取url中的参数
function getParams( url, key )
{
	var url = url.replace( '?', '&' ).split( '&' );
	var paramsObj = {};
	for( var i = 0, iLen = url.length; i < iLen; i++ )
	{
		var param = url[ i ].split( '=' );
		paramsObj[ param[ 0 ] ] = param[ 1 ];
	}
	if( key )
	{
		return decodeURI( paramsObj[ key ] );
	}
}
//毫秒转化为yyyy-MM-dd HH:mm:ss(可指定转化形式)
var format = function( time, format )
{
	var t = new Date( time );
	var tf = function( i )
	{
		return (i < 10 ? '0' : '') + i
	};
	return format.replace( /yyyy|MM|dd|HH|mm|ss/g, function( a )
	{
		switch( a )
		{
			case 'yyyy':
				return tf( t.getFullYear() );
				break;
			case 'MM':
				return tf( t.getMonth() + 1 );
				break;
			case 'mm':
				return tf( t.getMinutes() );
				break;
			case 'dd':
				return tf( t.getDate() );
				break;
			case 'HH':
				return tf( t.getHours() );
				break;
			case 'ss':
				return tf( t.getSeconds() );
				break;
		}
	} )
};
//弹窗出现
function popShow( parm )
{
	$( ".grey," + parm ).removeClass( "hide" );
}
//弹窗关闭
function popHide()
{
	$( ".grey,.popUp" ).addClass( "hide" );
}
//修改资料
$( document ).on( 'click', '.modifiMsgPop .btnArea .btn', function()
{
	var nickName = $( "#nickname" ).val();console.log(nickName.length);
	var sign = $( "#sign" ).val();
	var phone = $( "#phone" ).val();
	if( nickName == "" || nickName.replace( /\s/g, "" ) == "" )
	{
		$.tooltip( '请输入昵称' );
		return;
	}
	if( sign == "" || sign.replace( /\s/g, "" ) == "" )
	{
		$.tooltip( '请输入个性签名' );
		return;
	}
	var isMobile = new RegExp( /^1[34578]\d{9}$/ );
	if( phone == "" || phone.replace( /\s/g, "" ) == "" )
	{
		$.tooltip( '请输入手机号' );
		return;
	}
	if( !isMobile.test( phone ) )
	{
		$.tooltip( '请输入正确的手机号' );
		return;
	}
	var usercode = getStorage( "usercode" );
	var img = $( '.modifiMsgPop .headOuter img' ).attr( 'src' );
	var dataJson = {
		"usercode": usercode,
		"nickname": nickName,
		"sign": sign,
		"mobile": phone,
		"icon": img
	};
	$.ajax( {
		type: 'post',
		url: ajaxUrl + '/p-info/updateUserInfo',
		data: dataJson,
		beforeSend: function()
		{
			loading( "rgba(0,0,0,0.66)", "spinner1" );
		},
		complete: function()
		{
			loading_success();
		},
		success: function( a )
		{
			if( a.code == 0 )
			{
				popHide();
				layer.msg( "提交成功" );
				//重新加载用户信息
				getUserMsg();
			}
			else
			{
				$.tooltip( a.message )
			}
		},
		error: function()
		{
			$.dialog( 'alert', '错误', '服务器走丢了', 1500 );
		}
	} )
} );

//更改手机号-发送验证码
$(document).on("click",".modifiPhonePop .send-code",function(){
	var usercode = getStorage("usercode");
	var newPhone = $("#newPhone").val();
	var imgCode = $("#imgCode").val();
	var isMobile = new RegExp( /^1[34578]\d{9}$/ );
	if( newPhone == "" || newPhone.replace( /\s/g, "" ) == "" )
	{
		$.tooltip( '请输入手机号' );
		return;
	}
	if( !isMobile.test( newPhone ) )
	{
		$.tooltip( '请输入正确的手机号' );
		return;
	}
	if( imgCode == "" || imgCode.replace( /\s/g, "" ) == "" )
	{
		$.tooltip( '请输入图片验证码' );
		return;
	}
	var dataJson= {"usercode" : usercode,"verifyCode":imgCode,"newMobile":newPhone};
	ajax_sendCode(dataJson,this,"/user/updateMobileSmsCode");
});
//更改手机号 - 确定
$(document).on("click",".modifiPhonePop .btnArea .btn",function(){
	var usercode = getStorage("usercode");
	var newPhone = $("#newPhone").val();
	var smscode = $("#authCode").val();
	var isMobile = new RegExp( /^1[34578]\d{9}$/ );
	if( newPhone == "" || newPhone.replace( /\s/g, "" ) == "" )
	{
		$.tooltip( '请输入手机号' );
		return;
	}
	if( !isMobile.test( newPhone ) )
	{
		$.tooltip( '请输入正确的手机号' );
		return;
	}
	if( smscode == "" || smscode.replace( /\s/g, "" ) == "" )
	{
		$.tooltip( '请输入短信验证码' );
		return;
	}
	var dataJson= {"updateMobile":1,"usercode" : usercode,"newMobile":newPhone,"smscode":smscode};
	$.ajax({
		url:ajaxUrl+'/p-info/updateUserInfo',
		type:'post',
		data:dataJson,
		success:function(data){
			if(data.code == 0){
				popHide();
				$.tooltip('操作成功,1s后跳转至登录页面',2000,true,function(){
					//清除登录缓存并跳转登录页面
					localStorage.removeItem( "loginFlag" );
					localStorage.removeItem( "loginTime" );
					localStorage.removeItem( "userMsg" );
					window.location.href = '../login/login.html';
				});
			}else{
				 $.tooltip(data.message);
			}
		},
		error:function(){
			$.dialog( 'alert', '错误', '服务器走丢了', 1500 );
		}
	})
	
});

//点击header右边出现提交新单弹窗
$( document ).on( 'click', '.head-right2 .releaseIcon,.submitNewBtn', function()
{
	if($(this).hasClass("unable")){//当前账户禁用，无法提交新单
		$.tooltip( "您的账户当前处于禁用状态，无法提交新单" );
	}else{
		popShow( '.submitNewPop' );
	}
} );
//提交新单
$( document ).on( 'click', '.submitNewPop .btnArea .btn', function()
{
	var usercode = getStorage( "usercode" );
	var userMsg = JSON.parse( getStorage( "userMsg" ) );
	var nickname = userMsg.nickname;
	var goodsIcon = $( ".submitNewPop .headOuter:nth-child(1) img" ).attr( "src" );//商品图url
	var wenanIcon = $( ".submitNewPop .headOuter:nth-child(2) img" ).attr( "src" ).replace( "http://img.taobao218.com/", "" );//文案图url
	var title = $( "#title" ).val();
	var originalPrice = $( "#originalPrice" ).val();
	var presenPrice = $( "#presenPrice" ).val();
	var couponUrl = $( "#couponUrl" ).val();
	var productUrl = $( "#productUrl" ).val();
	var copywriting = $( "#copywriting" ).val();
	var brokerage = $( "#brokerage" ).val();
	
	if( goodsIcon == "../../img/head_upload.png" )
	{
		$.tooltip( "请上传商品图" );
		return false;
	}
	if( wenanIcon == "../../img/head_upload.png" )
	{
		$.tooltip( "请上传文案图" );
		return false;
	}
	if( title == "" || title.replace( /\s/g, "" ) == "" )
	{
		$.tooltip( "请输入标题" );
		return false;
	}
	if( originalPrice == "" || originalPrice.replace( /\s/g, "" ) == "" )
	{
		$.tooltip( "请输入原价" );
		return false;
	}
	if( presenPrice == "" || presenPrice.replace( /\s/g, "" ) == "" )
	{
		$.tooltip( "请输入券后价" );
		return false;
	}
	if( couponUrl == "" || couponUrl.replace( /\s/g, "" ) == "" )
	{
		$.tooltip( "请输入优惠券链接" );
		return false;
	}
	if( productUrl == "" || productUrl.replace( /\s/g, "" ) == "" )
	{
		$.tooltip( "请输入商品链接" );
		return false;
	}
	if( copywriting == "" || copywriting.replace( /\s/g, "" ) == "" )
	{
		$.tooltip( "请输入文案" );
		return false;
	}
	if( brokerage == "" || brokerage.replace( /\s/g, "" ) == "" )
	{
		$.tooltip( "请输入佣金" );
		return false;
	}
	var brokerageType = $( ".brokerageType .active" ).attr( "data-sort" );//佣金类型
	var activeSync = $( ".activeSync .active" ).attr( "data-sort" );//活动是否同步
	var activeType = $( ".activeTypeOuter .active" ).attr( "data-sort" );//活动类型
	//活动不同步，则活动类型为0-普通
	if( activeSync == 0 )
	{
		activeType = 0;
	}

	var dataJson = {
		"usercode": usercode,
		"submitPerson": nickname,
		"img": goodsIcon,
		"img2": wenanIcon,
		"goodName": title,
		"price": originalPrice,//原价
		"voucherPrice": presenPrice,//券后价格
		"couponLink": couponUrl,
		"goodLink": productUrl,
		"message": copywriting,//文案
		"commissionProportion": brokerage,//佣金比例
		"commissionType": brokerageType,//佣金类型 1-通用 2-定向 3-鹊桥 4-营销
		"goodType": activeType //活动类型  1聚划算  2淘抢购  0普通
	};
	$.ajax( {
		type: 'post',
		url: ajaxUrl + '/user/goods/addAd',
		data: dataJson,
		beforeSend: function()
		{
			loading( "rgba(0,0,0,0.66)", "spinner1" );
		},
		complete: function()
		{
			loading_success();
		},
		success: function( a )
		{
			console.log( JSON.stringify( a ) );
			if( a.errorCode == 200 )
			{
				popHide();
				layer.msg( "提交成功" );
				//刷新页面
				getUserMsg( 1 );
					
			}
			else
			{
				$.tooltip( a.moreInfo );
			}
		},
		error: function()
		{
			$.dialog( 'alert', '错误', '服务器走丢了', 1500 );
		}
	} )

} );

//提交新单时 佣金类型/活动同步/活动类型 单选
$( document ).on( 'click', '.submitNewPop .sorts .sort', function()
{
	$( this ).addClass( "active" ).siblings().removeClass( "active" );
	if( $( ".syncSort .sort:last-child" ).hasClass( "active" ) )
	{
		$( ".activeTypeOuter" ).hide();
	}
	else
	{
		$( ".activeTypeOuter" ).show();
	}
} );

//管理员-审核操作-点击打回or通过
function passOrRefuse( parm )
{
	var couponId = $( parm ).attr( "couponId" );
	var createTime = $( parm ).attr( "createTime" );
	var usercode = $( parm ).attr( "usercode" );
	var goodName = $( parm ).parents( ".item" ).find( "h1 a" ).text();
	var mUsercode = getStorage( "usercode" );
	var dataJson = {};
	if( $( parm ).hasClass( "pass" ) )
	{//通过
		popShow( ".checkPassPop" );//弹窗出现
		$( document ).on( 'click', '.checkPassPop .btnArea .btn', function()
		{
			dataJson = {
				"roleId": 2,
				"couponId": couponId,
				"examine_status": 2,
				"reduce": 0,
				"createTime": createTime,
				"usercode": usercode,
				"goodName": goodName,
				"mUsercode": mUsercode
			};
			checkAjax( dataJson );
		} );

	}
	else
	{//打回
		popShow( ".checkRefusePop" );//弹窗出现
		$( document ).on( 'click', '.checkRefusePop .btnArea .btn', function()
		{
			if( !$( ".checkRefusePop .select .iconfont" ).hasClass( "selected" ) )
			{
				$.tooltip( '请选择是否扣分' );
				return;
			}
			var index = $( ".checkRefusePop .iconfont.selected" ).attr( "data-index" );
			dataJson = {
				"roleId": 2,
				"couponId": couponId,
				"examine_status": 3,
				"reduce": index,
				"createTime": createTime,
				"usercode": usercode,
				"goodName": goodName,
				"mUsercode": mUsercode
			};
			checkAjax( dataJson );
		} );
	}
}

//管理员-审核具体交互
function checkAjax( dataJson )
{
	$.ajax( {
		type: 'post',
		url: ajaxUrl + '/p-info/badGoods',
		data: dataJson,
		beforeSend: function()
		{
			loading( "rgba(0,0,0,0.66)", "spinner1" );
		},
		complete: function()
		{
			loading_success();
		},
		success: function( a )
		{
			console.log( JSON.stringify( a ) );
			if( a.code == 0 )
			{
				popHide();
				layer.msg( "操作成功" );
				//重新加载列表
				get_examineManage_goods( 1, 1, format( new Date(), "yyyy-MM-dd" ) );
			}
		},
		error: function()
		{
			$.dialog( 'alert', '错误', '服务器走丢了', 1500 );
		}
	} )
}

//打回是否扣分切换
$( ".checkRefusePop .select .iconfont" ).click( function()
{
	$( this ).addClass( "selected" ).html( "&#xe62b;" ).siblings( "i" ).removeClass( "selected" ).html( "&#xe7b4;" );
} );

//管理员-下架
function downShelf( parm )
{
	var mUsercode = getStorage("usercode");
	popShow( ".downShelfPop" );//弹窗出现
	var item = $( parm ).parents( ".item" );
	var itemid = item.attr( "itemid" );
	$( document ).on( 'click', '.downShelfPop .btnArea .btn', function()
	{
		$.ajax( {
			type: "POST",
			url: ajaxUrl + "/p-info/deleteGoods",
			data: { "roleId": 2, "item_id": itemid,"mUsercode":mUsercode },
			success: function( data )
			{
				console.log( JSON.stringify( data ) );
				
				if( data.code == 0 )
				{
					popHide();
					layer.msg( "已下架" );
					item.remove();
				}
				else
				{
					$.tooltip( data.message );
				}
			},
			error: function( data )
			{
				$.dialog( 'alert', '错误', '服务器走丢了', 1500 );
			}
		} );
	} );
}

//跳转系统消息页面
$( ".head-right2 .informIcon,.head-right2 .informNum" ).click( function()
{
	location.href = "user_message.html";
} );
var userMsg = JSON.parse( getStorage( "userMsg" ) );

//点击用户头像跳转个人页面-根据身份判断
$( ".head-right2 .headPic" ).click( function()
{
	var rolecode = userMsg.rolecode;
	if( rolecode == 1 )
	{
		location.href = "userPersonalCenter.html";
	}
	else
	{
		location.href = "adminPersonalCenter.html";
	}
} );

//出现审核按钮
$( document ).on( 'mouseenter', '.goods-wrap .checkItem', function()
{
	var copyBtn = $( this ).find( '.btnArea' );
	if( copyBtn.is( ":hidden" ) )
	{
		copyBtn.slideDown( 400 );
	}
	/*$( this ).find( ".submitPerson" ).show();*/
} );
//隐藏审核按钮
$( document ).on( 'mouseleave', '.goods-wrap .checkItem', function()
{
	var copyBtn = $( this ).find( '.btnArea' );
	copyBtn.slideUp( 400 );
	/*$( this ).find( ".submitPerson" ).hide();*/
} );
//退出登录
$( ".signOutBtn" ).click( function()
{
	layer.msg( '确定要退出吗？', {
		time: 0 //不自动关闭
		, btn: [ '是的', '取消' ]
		, yes: function( index )
		{
			layer.close( index );
			localStorage.removeItem( "userMsg" );
			localStorage.removeItem( "usercode" );
			localStorage.removeItem( "loginFlag" );
			localStorage.removeItem( "loginTime" );
			location.href = "index.html";
		}
	} );
} );

//我的选品出现/隐藏
$( ".mySelection .shrinkBtn" ).click( function()
{
	var mySelection = $( '.mySelection' );
	if( mySelection.hasClass( "active" ) )
	{
		mySelection.animate( { right: '-310px' }, 200 ).removeClass( "active" );
	}
	else
	{
		mySelection.animate( { right: '0px' }, 200 ).addClass( "active" );
	}
} );
//加入选品
$( document ).on( 'click', '.add-btn', function()
{
	var $this = $( this );
	//判断是否登录状态
	var userMsg = JSON.parse( getStorage( "userMsg" ) );
	if( $( ".head-right" ).is( ":visible" ) )
	{//缓存不存在
		$.tooltip( '请先登录' );
	}
	else
	{
		var token = userMsg.token;
		var mobile = userMsg.mobile;
		//token验证
		$.ajax( {
			type: "POST",
			url: ajaxUrl + "/user/tlogin",
			data: { "token": token, "mobile": mobile },
			success: function( data )
			{
				console.log( JSON.stringify( data ) );
				if( data.code == 0 )
				{//验证成功，加入选品
					var usercode = getStorage( "usercode" );
					var itemId = $this.parents( ".item" ).attr( "itemid" );
					var couponId = $this.parents( ".item" ).attr( "couponid" );
					console.log( usercode, itemId, couponId );
					$.ajax( {
						type: "POST",
						url: ajaxUrl + "/p-info/addCollection",
						data: { "usercode": usercode, "itemId": itemId, "couponId": couponId },
						success: function( data )
						{
							console.log( JSON.stringify( data ) );
							if( data.code == 0 )
							{
								layer.msg( "加入成功" );
								getCollection();//重新获取选品
							}
							else
							{
								$.tooltip( data.message );
							}
						},
						error: function( data )
						{
							$.dialog( 'alert', '错误', '服务器走丢了', 1500 );
						}
					} );

				}
				else
				{//验证不成功
					$.tooltip( '请先登录' );
				}
			},
			error: function( data )
			{
				$.dialog( 'alert', '错误', '服务器走丢了', 1500 );
			}
		} );
	}

} );
//获取选品
function getCollection()
{
	var usercode = getStorage( "usercode" );
	$.ajax( {
		type: "POST",
		url: ajaxUrl + "/p-info/getCollection",
		data: { "usercode": usercode, "pageIndex": 1 },
		success: function( data )
		{
			console.log( JSON.stringify( data ) );
			if( data.code == 0 )
			{
				var count = data.data.count;
				$( ".selectionNum" ).text( count );
				var collections = data.data.data;
				if( collections.length != 0 )
				{
					var result = "";
					$.each( collections, function( i, collection )
					{
						var copyImg = collection.copyImg;
						var copyMessage = collection.message;
						var goodName = collection.goodName;
						var img = collection.img;
						var afterPrice = collection.afterPrice;
						var coupon_num = collection.coupon_num;
						var commission_type = getCommissionType( collection.commission_type );//佣金类型
						var commission_proportion = collection.commission_proportion;
						var itemId = collection.itemId;
						var shopType = collection.shopType;//活动类型
						var shopTypeImg = "", itemHref = "";
						if( shopType == 2 )
						{  // 天猫
							shopTypeImg = '../../img/tianmao.png';
							itemHref = "https://detail.tmall.com/item.htm?id=" + itemId;
						}
						else
						{  //  淘宝
							shopTypeImg = '../../img/taobao.png';
							itemHref = "https://item.taobao.com/item.htm?id=" + itemId;
						}
						result += '<div class="select-item"> ' +
											'<div class="title"> ' +
											'<img src="' + shopTypeImg + '" alt=""> ' +
											'<a target="_blank" href="' + itemHref + '"><span>' + goodName + '</span> </a> ' +
											'</div> ' +
											'<div class="body"> ' +
											'<div class="left imgOuter"> ' +
											'<a target="_blank" href="' + itemHref + '"><img src="' + img + '" alt=""> </a>' +
											'</div> ' +
											'<div class="left datasOuter"> ' +
											'<div class="left afterPrice">￥<span>' + afterPrice + '</span> <div>券后价</div> </div> ' +
											'<div class="left ">￥<span>' + coupon_num + '</span> <div>优惠券</div> </div> ' +
											'<div class="left ">￥<span>' + commission_proportion + '%</span><div>' + commission_type + '</div> </div> ' +
											'</div> ' +
											'</div> ' +
											'<i class="iconfont selectIcon" itemId=' + itemId + '>&#xe7b4;</i> ' +
											'<div class="btn gradient copyBtn" copy-data=\'<img src="http://img.taobao218.com/' + copyImg + '" >' + copyMessage + '\' data-clipboard-target=".copy-data">复制文案</div> ' +
											'</div>';
					} );
					$( ".mySelection .itemOuter" ).html( result );
					copy_int();//复制文案
				}
				else
				{
					var s = '<div class="no-data2">' +
									'<img src="../../img/no_data.png" alt="">' +
									'<div>这里空空如也~<div>' +
									'<div>';
					$( ".mySelection .itemOuter" ).html( s );

				}

			}
			else
			{
				$.tooltip( data.message );
			}
		},
		error: function( data )
		{
			$.dialog( 'alert', '错误', '服务器走丢了', 1500 );
		}
	} );
}

//选中选品
$( document ).on( 'click', '.mySelection .selectIcon', function()
{
	if( $( this ).hasClass( "selected" ) )
	{
		$( this ).removeClass( "selected" ).html( "&#xe7b4;" );
		var selectIcon = $( ".mySelection .selectIcon" );
		var i = selectIcon.length;
		selectIcon.each( function()
		{
			if( $( this ).hasClass( "selected" ) )
			{
				i--;
			}
		} );
		if( i == selectIcon.length )
		{
			$( ".mySelection .deleteBtn" ).removeClass( "active" );
		}
	}
	else
	{
		$( this ).addClass( "selected" ).html( "&#xe62b;" );
		$( ".mySelection .deleteBtn" ).addClass( "active" );
	}

} )
//删除选品
$( document ).on( "click", ".mySelection .deleteBtn.active", function()
{
	var usercode = getStorage( "usercode" );
	var selectIcons = $( ".selectIcon.selected" );
	var itemId = "";
	$.each( selectIcons, function( i, selectIcon )
	{
		if( i == selectIcons.length - 1 )
		{//最后一个，不加逗号
			itemId += $( this ).attr( "itemId" );
		}
		else
		{
			itemId += $( this ).attr( "itemId" ) + ",";
		}
	} );
	$.ajax( {
		type: "POST",
		url: ajaxUrl + "/p-info/deleteCollection",
		data: { "usercode": usercode, "itemId": itemId },
		success: function( data )
		{
			console.log( JSON.stringify( data ) );
			if( data.code == 0 )
			{
				layer.msg( "已删除" );
				//重新加载选品
				getCollection();
			}
			else
			{
				$.tooltip( data.message );
			}
		},
		error: function( data )
		{
			$.dialog( 'alert', '错误', '服务器走丢了', 1500 );
		}
	} );

} );

//通过token获取用户信息
function getUserMsg( rolecode )
{
	var userMsg = JSON.parse( getStorage( "userMsg" ) );
	var token = userMsg.token;
	var mobile = userMsg.mobile;
	//token验证
	$.ajax( {
		type: "POST",
		url: ajaxUrl + "/user/tlogin",
		data: { "token": token, "mobile": mobile },
		success: function( data )
		{
			console.log( JSON.stringify( data ) );
			if( data.code == 0 )
			{//验证成功
				var msg = data.data;
				var icon = msg.icon == "" || msg.icon == undefined ? '../../img/default_head.png' : msg.icon;
				var icon2 = msg.icon == "" || msg.icon == undefined ? '../../img/head_upload.png' : msg.icon;
				$( ".headOuter .icon,.head-right2 .headPic" ).attr( "src", icon );
				$( ".modifiMsgPop .uploadOuter img" ).attr( "src", icon2 );
				$( ".personalMsg .nickName" ).text( msg.nickname );
				$( "#nickname" ).val( msg.nickname );
				$( ".sign" ).text( msg.sign );
				$( "#sign" ).val( msg.sign );
				$( ".oldPhone" ).text( msg.mobile );
				var day = format( new Date(), 'yyyy-MM-dd' );
				if( rolecode == 1 )
				{//淘客
					$( ".point" ).text( msg.point + "积分" );
					$( "#pid" ).val( msg.pid );
					$( "#code" ).val( msg.referralcode );
					$( ".personalMsg .submitNum" ).text( msg.submitnum );
					$( ".personalMsg .passedNum" ).text( msg.passnum );
					$( ".personalMsg .checkNum" ).text( msg.examnum );
					if(msg.status==1){//禁用状态
						$(".disabledBtn").addClass("able").text("解除禁用");
					}
				}
				else
				{//管理员
					getThreeNum( day, 1 );//加载今日三个状态的单子数量
				}
			}
			else
			{//验证不成功
				$.tooltip( data.message,2500,false,function(){
					location.href = "index.html";
				} );
			}
		},
		error: function( data )
		{
			$.dialog( 'alert', '错误', '服务器走丢了', 1500 );
		}
	} );
}
//通过usercode获取用户信息
function getUserMsgBycode( usercode )
{
	$.ajax( {
		type: "POST",
		url: ajaxUrl + "/user/getUserInfo",
		data: { "usercode": usercode },
		success: function( data )
		{
			console.log( JSON.stringify( data ) );
			if( data.code == 0 )
			{
				var msg = data.data;
				var icon = msg.icon == "" || msg.icon == undefined ? '../../img/default_head.png' : msg.icon;
				$( ".headOuter .icon" ).attr( "src", icon );
				$( ".nickName" ).text( msg.nickname );
				$( ".sign" ).text( msg.sign );
				$( ".point" ).text( msg.point + "积分" );
				$( ".personalMsg .submitNum" ).text( msg.submitnum );
				$( ".personalMsg .passedNum" ).text( msg.passnum );
				$( ".personalMsg .checkNum" ).text( msg.examnum );
				if(msg.status==1){//禁用状态
					$(".disabledBtn").addClass("able").text("解除禁用");
				}
			}
			else
			{
				$.tooltip( data.message );
			}
		},
		error: function( data )
		{
			$.dialog( 'alert', '错误', '服务器走丢了', 1500 );
		}
	} );
}

//淘客-加载不同日期下三个状态单子的数量
function getThreeNum2( usercode, day )
{
	$.ajax( {
		type: "POST",
		url: ajaxUrl + "/user/difGoodsExamineStatusNum",
		data: { "usercode": usercode, "day": day },
		success: function( data )
		{
			console.log( JSON.stringify( data ) );
			if( data.code == 0 )
			{
				var needExamined = data.data.needExamined;
				var examnum = needExamined.examnum;
				var failednum = needExamined.failednum;
				var passnum = needExamined.passnum;
				$( ".statusSorts .checkNum" ).text( "（" + examnum + "）" );
				$( ".statusSorts .passedNum" ).text( "（" + passnum + "）" );
				$( ".statusSorts .repulseNum" ).text( "（" + failednum + "）" );
			}
			else
			{
				$.tooltip( data.message );
			}
		},
		error: function( data )
		{
			$.dialog( 'alert', '错误', '服务器走丢了', 1500 );
		}
	} );
}

//管理员-加载不同日期下三个状态单子的数量
function getThreeNum( day, flag )
{
	$.ajax( {
		type: "POST",
		url: ajaxUrl + "/user/todayNeedExamined",
		data: { "day": day },
		success: function( data )
		{
			console.log( JSON.stringify( data ) );
			if( data.code == 0 )
			{
				var needExamined = data.data.needExamined;
				var examnum = needExamined.examnum;
				var failednum = needExamined.failednum;
				var passnum = needExamined.passnum;
				if( flag == 1 )
				{//初次加载，flag=1，加载当日待审核数量
					$( ".personalMsg .checkNum" ).text( examnum );
				}
				$( ".statusSorts .checkNum" ).text( "（" + examnum + "）" );
				$( ".statusSorts .passedNum" ).text( "（" + passnum + "）" );
				$( ".statusSorts .repulseNum" ).text( "（" + failednum + "）" );
			}
			else
			{
				$.tooltip( data.message );
			}
		},
		error: function( data )
		{
			$.dialog( 'alert', '错误', '服务器走丢了', 1500 );
		}
	} );
}
//管理员-用户管理-获取三个状态的用户数量
function getThreeNum3()
{
	$.ajax( {
		type: "POST",
		url: ajaxUrl + "/p-info/difStatusUserNum",
		data: {},
		success: function( data )
		{
			console.log( JSON.stringify( data ) );
			if( data.code == 0 )
			{
				var normalNum = data.data.normalNum;
				var exceptionNum = data.data.exceptionNum;
				var all = normalNum + exceptionNum;
				$( ".statusSorts .allNum" ).text( "（" + all + "）" );
				$( ".statusSorts .normalNum" ).text( "（" + normalNum + "）" );
				$( ".statusSorts .frozenNum" ).text( "（" + exceptionNum + "）" );
				$( ".userNum .num" ).text( all );
			}
			else
			{
				$.tooltip( data.message );
			}
		},
		error: function( data )
		{
			$.dialog( 'alert', '错误', '服务器走丢了', 1500 );
		}
	} );
}

//时间选择-前一天
function previousDay()
{
	var layuiInput = $(".layui-input");
	var oldTime = new Date( layuiInput.val() ).getTime();
	var newTime = oldTime - 24 * 60 * 60 * 1000;
	layuiInput.val( format( newTime, 'yyyy-MM-dd' ) );
	return format( newTime, 'yyyy-MM-dd' );
}
//时间选择-后一天
function nextDay()
{
	var layuiInput = $(".layui-input");
	var oldTime = new Date( layuiInput.val() ).getTime();
	var newTime = oldTime + 24 * 60 * 60 * 1000;
	layuiInput.val( format( newTime, 'yyyy-MM-dd' ) );
	return format( newTime, 'yyyy-MM-dd' );
}

//localStorage-存储
function setStorage( name, value )
{
	if( !window.localStorage )
	{
		console.log( "浏览器不支持localStorage" );
	}
	else
	{
		localStorage.setItem( name, value );
	}
}
//localStorage-获取
function getStorage( name )
{
	console.log( localStorage );
	var val = localStorage.getItem( name );
	return val;
}

//上传图片
layui.use( 'upload', function()
{
	layui.upload( {
		elem: '.addimgIpt',
		url: '/p-info/upload',
		unwrap: true,
		before: function( input )
		{
			thisDom = input;
			//返回的参数，即为当前的input DOM对象
			layui.use( 'layer', function()
			{
				var layer = layui.layer;
				layer.msg( "<span style='color:#fff'>文件上传中</span>" );
			} );
		},
		success: function( res )
		{
			var ret = JSON.parse( res );
			console.log( $( thisDom ) );
			$( thisDom ).parents( ".uploadOuter" ).find( "img" ).attr( {
				'src': ret.data.url,
				'imageId': ret.data.imageId
			} );
		}
	} )
} );

//根据编号返回优惠券类型-1-通用 2-定向 3-鹊桥
function getCommissionType( id )
{
	switch( id )
	{
		case "1":
			return "通用";
			break;
		case "2":
			return "定向";
			break;
		case "3":
			return "鹊桥";
			break;
		case "4":
			return "营销";
			break;
	}
}


//请求url-本地
var ajaxUrl = "";



